package cn.edu.lingnan.demo.listener;

import cn.edu.lingnan.demo.entity.Student;
import cn.edu.lingnan.demo.service.StudentService;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import java.util.ArrayList;
import java.util.List;

/**
 *  * 有个很重要的点
 *  * DemoDataListener 不能被spring管理，
 *  * 要每次读取excel都要new,然后里面用到spring可以构造方法传进去
 *
 * @author wuyuan
 * @since 2020-05-29 22:08
 */
public class StudentExcelListener extends AnalysisEventListener<Student> {
    public StudentExcelListener(StudentService studentService) {
        this.studentService = studentService;
    }
    private List<Student> studentList = new ArrayList<>();
    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final Integer BATCH_COUNT = 5;
    private StudentService studentService;

     /* 这个每一条数据解析都会来调用
     *
     * @param data
     *  one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(Student student, AnalysisContext analysisContext) {
        //解析数据保存到List<student>
        studentList.add(student);
        System.out.println();
        System.out.println(studentList);

        System.out.println();


        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
//        if (studentList.size() >= BATCH_COUNT) {
//            // 存储完成清理 list
//            studentList.clear();
//        }
    }

    /**
     *   所以数据解释完都会来调用
     *@param analysisContext
     *@return void
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //当Excel解析完毕后，执行
        System.out.println(studentList);
        if (studentService != null) {
            studentService.insert(studentList);
        }
    }

}
